<?php

	if( empty($_POST)){
?>

<head>
	<title>Sagez</title>
	<LINK href="style.css" rel="stylesheet" type="text/css">
	<script src="http://pajhome.org.uk/crypt/md5/2.2/md5-min.js" type="text/javascript"></script>

	<script type="text/javascript">

	function validate(){
		 var user = document.forms["loginForm"]["user"].value;
		 var pass = document.forms["loginForm"]["pass"].value;

		 if(user==null || user=="" || pass=="null" || pass==""){
		 	       alert("Enter the username and password you wish to register with");
			       return false;
			       
		 }
		 //if the user / pass are filled then hash it and submit the form
		 hash();
		 document.getElementById('registerCheckbox').checked = true;
		 document.forms["loginForm"].submit();
		 

	}

	function hash(){
		 document.getElementsByName('pass')[0].value = hex_md5(document.getElementsByName('pass')[0].value);
	}
	</script>

</head>

<body>
<div class="login">
	<image src="images/sagez.png" width="300"/>

	<form name="loginForm" method="post" >
		Username: <input type="text" name="user" />     <br/>
		Password: <input type="password" name="pass" /> <br/>
		<input type="checkbox" value="true" name="register" style="visibility:hidden" id="registerCheckbox"/>
		<input type="submit" value="Log in" onclick="hash();document.getElementById('registerCheckbox').checked = false;" />
		<input type="button" value="Register" onclick="validate();" />
	</form> 


</div>
</body>

<?php
	}else{
		
		$db = mysql_connect('localhost', 'sagez', 'Door4All!') or die('Could not connect: ' . mysql_error());
		mysql_select_db("sagez") or die(mysql_error());

		if($_POST['register'] == 'true'){

			$query = sprintf("insert into users (username, password) values('%s', '%s');", $_POST['user'], $_POST['pass']);
			
			if(mysql_query($query))
				echo "Successfully added " . $_POST['user'] . ", you may now login!"; 
			else
				echo "User already exists";

		}else{
		
			$query = sprintf("select * from users where username='%s' AND password='%s' ;", $_POST['user'], $_POST['pass']);
			$data = mysql_query($query);		


			$info = mysql_fetch_array( $data );	
			if( $info['username'] == $_POST['user'])
				echo "hello " .$_POST['user'];				
			else{
				echo "Incorrect username or password";

			}

						
		}

		mysql_close($db);
	}

	


?>